import nodePath from "path";
import nodeFileSys from "fs";
import {codeSiteList} from "./data-var-list/code-site-list";
import {mostUseSiteList} from "./data-var-list/most-use-site-list";
import {domainRootList} from "./data-var-list/domain-root-list";
import {blockSiteList} from "./block-list/block-list";
import {CRLF} from "./var";
import {directSiteList} from "./direct-list/direct-ip-list";
function stringListSort(list: string[]): string[] {
    return rebuildFromSet(list).sort((a, b) => {
       if (b > a) {
           return -1;
       }
       return 1;
    });
}

function rebuildFromSet(arr: string[]): string[] {
    return Array.from(new Set(arr));
}

const ruleFileDir = nodePath.join(__dirname, "../surge-rule");
const list: string[] = stringListSort(codeSiteList).concat(stringListSort(mostUseSiteList)).concat(stringListSort(domainRootList));
let data = stringListSort(blockSiteList).map((item) => {
    return `DOMAIN-SUFFIX,${item},REJECT`;
}).join(CRLF);
data += CRLF;
data += stringListSort(directSiteList).map((item) => {
    return `DOMAIN-SUFFIX,${item},DIRECT`;
}).join(CRLF);
data += CRLF;
data += list.map((item) => {
    return `DOMAIN-SUFFIX,${item},ssr`;
}).join(CRLF);
data += CRLF + "FINAL,DIRECT";

nodeFileSys.promises.writeFile(nodePath.join(ruleFileDir, "Surge.rule"), data, "utf8").then(() => {
    console.log("write okay");
}).catch((err) => {
    console.error("write error");
    console.error(err);
});
